package mmc.resource;

import static org.lwjgl.opengl.GL11.*;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Map;

import org.lwjgl.opengl.GL11;

public class Alphabet12p extends Texture{

	public static final int CHAR_WIDTH = 10, CHAR_HEIGHT = 12;
	public static final int WIDTH = 512, HEIGHT = 512;
	public static final Map<Character,Integer> charPositions = new HashMap<Character, Integer>();
	
	static{
		for(char i=0;i>=0;i++){
			int xPos = ((i*CHAR_WIDTH)%(WIDTH-2));
			int yPos = ((i*CHAR_WIDTH)/(WIDTH-2)) * CHAR_HEIGHT;
			
			if(xPos>=WIDTH||yPos>=HEIGHT-CHAR_HEIGHT)
				break;
			
			//System.out.println("adding char '"+i+"' to "+xPos+"/"+yPos);
			
			yPos<<=Integer.SIZE/2;
			
			charPositions.put(i, xPos|yPos);
		}
	}
	
	private Alphabet12p() {
		super(glGenTextures());
		
		int[] data = new int[WIDTH*HEIGHT*4]; //ARGB
		buildImage().getData().getPixels(0, 0, WIDTH, HEIGHT, data);
		
		ByteBuffer buffer = ByteBuffer.allocateDirect(WIDTH*HEIGHT*4); //RGBA
		buffer.order(ByteOrder.nativeOrder());
		for(int i=0;i<WIDTH*HEIGHT;i++){
			buffer.put((byte)data[i*4+1]); //R
			buffer.put((byte)data[i*4+2]); //G
			buffer.put((byte)data[i*4+3]); //B
			buffer.put((byte)data[i*4]);   //A
		}
		buffer.flip();
		
		glBindTexture(GL_TEXTURE_2D,id);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, WIDTH, HEIGHT, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
	}
	
	private BufferedImage buildImage(){
		BufferedImage b = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);
		Graphics g = b.getGraphics();
		g.setFont(new Font(Font.MONOSPACED,Font.BOLD,12));
		
		for(Character ch : charPositions.keySet()){
			int posx=charPositions.get(ch);
			int posy=posx>>Integer.SIZE/2;
			posx &= (1<<Integer.SIZE/2)-1;
			
			g.drawString(new String(new char[]{ch}), posx+2, posy+CHAR_HEIGHT-2);
		}
		
		return b;
	}
	
	private static Alphabet12p THIS;
	
	public static Alphabet12p getAlphabetTexture(){
		if(THIS==null)
			THIS = new Alphabet12p();
		
		return THIS;
	}
	
	
}
